/*
 * Copyright (C) 2013 TinhVan Outsourcing.
 */
package com.android.friend.lib.network.httptask;

import java.lang.ref.WeakReference;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.view.WindowManager;

import com.android.friend.lib.network.util.AndroidVersionUtils;

/**
 * 
 * @author HuanND
 * @param <Params>
 * @param <Progress>
 * @param <Result>
 */
public abstract class BaseTask<Params, Progress, Result> extends AsyncTask<Params, Progress, Result> {
    protected ProgressDialog mDialog;
    protected WeakReference<Context> mContext = new WeakReference<Context>(null);
    private boolean isShowLoading = true;

    public BaseTask(Context pContext, boolean pShowLoading) {
        this.mContext = new WeakReference<Context>(pContext);
        this.isShowLoading = pShowLoading;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        if (isShowLoading) {
            mDialog = new ProgressDialog(mContext.get());
            mDialog.setCancelable(false);
            try {
                mDialog.show();
            } catch (WindowManager.BadTokenException e) {} catch (Exception e) {}
        }
    }

    @Override
    protected void onPostExecute(Result result) {
        super.onPostExecute(result);
        try {
            if (isShowLoading && mDialog != null && mDialog.isShowing()) {
                mDialog.dismiss();
                mDialog = null;
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    public void run(Params... params) {
        this.running(params);
    }

    private void running(Params... params) {
        if (AndroidVersionUtils.isBeforeHoneycomb()) {
            this.execute(params);
        } else {
            this.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
        }
    }
    
}
